package com.heima.wemedia.service.impl;


import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.wemedia.dtos.SensitiveDto;
import com.heima.model.wemedia.pageQuery.MediaPageQuery;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.service.WmSensitiveService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * @author Administrator
 */
@Service
public class WmSensitiveServiceImpl extends ServiceImpl<WmSensitiveMapper, WmSensitive> implements WmSensitiveService {
    @Autowired
    private WmSensitiveMapper wmSensitiveMapper;

    @Override
    public PageResponseResult pageByName( MediaPageQuery mediaPageQuery) {
        PageHelper.startPage(mediaPageQuery.getPage(), mediaPageQuery.getSize());
        List<WmSensitive> list = wmSensitiveMapper.pageByName(mediaPageQuery.getName());
        Page<WmSensitive> pageResult= (Page<WmSensitive>)list;
        long total = pageResult.getTotal();
        PageResponseResult responseResult = new PageResponseResult(mediaPageQuery.getPage(),mediaPageQuery.getSize(),Integer.parseInt(total+""));
        responseResult.setCode(200);
        responseResult.setData(pageResult.getResult());

        return  responseResult;
    }

    @Override
    public boolean save(SensitiveDto dto) {
        Long count = lambdaQuery()
                .eq(WmSensitive::getSensitives, dto.getName())
                .count();
        if (count!=null&&count>0){
            throw new RuntimeException("敏感词已存在");
        }
        WmSensitive wmSensitive = new WmSensitive();
        wmSensitive.setSensitives(dto.getName());
        wmSensitive.setCreatedTime(new Date());
        return this.save(wmSensitive);
    }

    @Override
    public boolean updateNameById(WmSensitive wmSensitive) {
        //先查查询是否存在
        WmSensitive sensitive = lambdaQuery().eq(WmSensitive::getId,wmSensitive.getId()).one();
       if (sensitive==null){
           throw new RuntimeException("敏感词不存在");
       }
        Long count = lambdaQuery()
                .eq(WmSensitive::getSensitives,wmSensitive.getSensitives())
                .ne(WmSensitive::getId,wmSensitive.getId())
                .count();
        if (count!=null&&count>0){
            throw new RuntimeException("敏感词已存在");

        }
        return updateById(wmSensitive);
    }
}
